package org.example.juc;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * JDK 实现代码块同步( 优先使用synchronized, 除非需要使用ReentrantLock的高级功能 )
 * @author 张琪
 * @date 2024/4/17 18:04
 */
public class LockExample {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(5);

        LockExample lockExample = new LockExample();

        executorService.execute(lockExample::test);
        executorService.execute(lockExample::test);
    }

    private Lock lock = new ReentrantLock();

    public void test() {
        // 手动上锁, 相当于锁代码块;
        lock.lock();
        try {
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + "  " + i);
            }
        } finally {
            lock.unlock();
        }
    }

}
